package com.cloud.nacosConfigLoad;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class HotBeanClassLoader extends ClassLoader {

    private File classDirectory;

    public HotBeanClassLoader(File classDirectory) {
        super(null); // 使用 null 作为父类加载器，确保完全绕过父类加载器
        this.classDirectory = classDirectory;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            // 将类名转换为文件路径
            String classPath = name.replace('.', File.separatorChar) + ".class";
            File classFile = new File(classDirectory, classPath);

            // 读取字节数据
            byte[] classData = loadClassData(classFile);

            return defineClass(name, classData, 0, classData.length);
        } catch (IOException e) {
            throw new ClassNotFoundException("Class not found: " + name, e);
        }
    }

    private byte[] loadClassData(File classFile) throws IOException {
        try (FileInputStream fis = new FileInputStream(classFile);
             FileChannel fileChannel = fis.getChannel()) {
            ByteBuffer byteBuffer = ByteBuffer.allocate((int) fileChannel.size());
            fileChannel.read(byteBuffer);
            return byteBuffer.array();
        }
    }
}
